import 'dart:io';

import 'package:asmore/route/artwork_screen.dart';
import 'package:asmore/route/settings_screen.dart';
import 'package:asmore/util.dart';
import 'package:asmore/work_card.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:asmore/library.dart';

import 'music.dart';

var logger = Logger();

void main() {
  logger.d("Logger is working!");
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AsMore',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: '播放器'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _prefs = SharedPreferences.getInstance();
  String? _dir;

  ValueNotifier<Artwork?> work = ValueNotifier(null);

  Future<void> _setDir(String dir) async {
    final SharedPreferences prefs = await _prefs;
    await prefs.setString("dir", dir);
    setState(() {
      _dir = dir;
    });
  }

  void selectRJ(int index) {
    setState(() {
      work.value = artworks[index];
    });
  }

  void _showAppBarMenu(BuildContext context) {
    showMenu(
      context: context,
      position: RelativeRect.fromRect(
        Rect.fromPoints(
          Offset.zero,
          Offset.zero,
        ),
        Offset.zero & Size.infinite,
      ),
      items: <PopupMenuItem<String>>[
        PopupMenuItem(
          value: '设置',
          child: Text('设置'),
          onTap: () {
            Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => SettingsScreen()));
          },
        ),
        // Add more menu items here
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    _prefs.then((value) => {
          super.setState(() {
            _dir = value.getString("dir");
          })
        }).then((value) {
      requestPermission().then((value) {
        if (_dir != null) scan(Directory(_dir!));
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.menu),
            iconSize: 30.0,
            onPressed: () {
              _showAppBarMenu(context);
            },
          ),
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              _dir == null ? "你还未添加库存，请前往设置" : "已设置目录$_dir",
            ),
            Expanded(
                child: GridView.builder(
                    itemCount: artworks.length, // 总的项目数量
                    itemBuilder: (BuildContext context, int index) {
                      getWorkInfo("RJ${artworks[index].id}", artworks[index]);
                      return WorkCard(
                          work: artworks[index],
                          onTap: () {
                            work.value = artworks[index];
                            Navigator.of(context).push(MaterialPageRoute(
                                builder: (context) => ArtworkScreen(work)));
                          });
                    },
                    gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                      maxCrossAxisExtent: 400, // 最大交叉轴尺寸（宽度）
                      mainAxisSpacing: 2,
                      crossAxisSpacing: 2,
                      childAspectRatio:
                          (MediaQuery.of(context).size.width / 400.0)
                              .clamp(0.5, 1.0),
                    ) // 根据屏幕宽度动态调整子项宽高比),
                    )),
          ],
        ),
      ),
      bottomNavigationBar: MusicPlayerControlBar(work),
    );
  }
}
